'use strict';

const db = uniCloud.database()
const dbCmd = db.command
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('云函数已被调用')
  console.log('===DEBUG CONTEXT===', context)

  // 1. 获取 token
  const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
  if (!token) {
    return {
      code: 401,
      msg: '未携带token',
      data: null
    }
  }

  // 2. 解析 token
  const uniId = uniIdCommon.createInstance({ context })
  const tokenRes = await uniId.checkToken(token)
  if (tokenRes.code !== 0) {
    return {
      code: 401,
      msg: 'token无效或已过期',
      data: null
    }
  }
  const uid = tokenRes.uid

  const { amount, paymentMethod, taskInfo, type } = event
  const amt = Number(amount)
  if (!uid) {
    return {
      code: 401,
      msg: '用户未登录',
      data: null
    }
  }
  if (isNaN(amt) || amt <= 0) {
    return { code: 400, msg: '金额无效' }
  }

  // 生成支付订单ID
  const paymentId = `PAY_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

  try {
    // 充值逻辑
    if (type === 'recharge') {
      // 增加余额
      await db.collection('uni-id-users').doc(uid).update({
        balance: dbCmd.inc(amt)
      })
      // 记录充值
      await db.collection('payment_records').add({
        payment_id: paymentId,
        user_id: uid,
        amount: amt,
        payment_method: paymentMethod,
        type: 'recharge',
        status: 'success',
        create_time: Date.now(),
        desc: '钱包充值'
      })
      return {
        code: 200,
        msg: '充值成功',
        data: { paymentId, amount: amt, method: paymentMethod }
      }
    }

    // 获取用户信息
    const userResult = await db.collection('uni-id-users').doc(uid).get()
    if (!userResult.data || userResult.data.length === 0) {
      return {
        code: 404,
        msg: '用户信息不存在'
      }
    }
    const user = userResult.data[0]

    // 支付逻辑
    if (paymentMethod === 'wallet') {
      if (user.balance < amt) {
        return {
          code: 400,
          msg: '余额不足，请充值或选择其他支付方式',
          data: { needed: amt - user.balance, balance: user.balance }
        }
      }
      // 扣除余额
      await db.collection('uni-id-users').doc(uid).update({
        balance: dbCmd.inc(-amt)
      })
      // 记录支付
      await db.collection('payment_records').add({
        payment_id: paymentId,
        user_id: uid,
        amount: amt,
        payment_method: paymentMethod,
        type: type,
        status: 'success',
        task_info: taskInfo,
        create_time: Date.now(),
        desc: '任务支付'
      })
      return {
        code: 200,
        msg: '支付成功',
        data: { paymentId, amount: amt, method: paymentMethod }
      }
    }

    // 其他支付方式（如微信、支付宝）可按需补充
    if (paymentMethod === 'wechat' || paymentMethod === 'alipay') {
      // 这里只做模拟，实际应集成第三方支付SDK
      await db.collection('payment_records').add({
        payment_id: paymentId,
        user_id: uid,
        amount: amt,
        payment_method: paymentMethod,
        type: type,
        status: 'pending',
        task_info: taskInfo,
        create_time: Date.now(),
        desc: '第三方支付（模拟）'
      })
      return {
        code: 200,
        msg: '模拟支付成功',
        data: { paymentId, amount: amt, method: paymentMethod }
      }
    }

    return { code: 400, msg: '不支持的支付方式' }
  } catch (error) {
    console.error('支付处理失败：', error)
    return {
      code: 500,
      msg: '支付处理失败，请重试'
    }
  }
} 